<template>
  <div>
    <el-card shadow="always" style="margin: 20px 0">
      <CategorySelect @getcategoryId="getcategoryId" :isshow='isshowtable'></CategorySelect>
    </el-card>
   
    <el-card shadow="always">
      <div v-show="isshowtable">
        <el-button type="primary" icon="el-icon-plus" @click="addAttr"
           :disabled='!id3'>添加属性</el-button
        >
        <el-table :data="attrList" border style="width: 100%; margin: 20px 0">
          <el-table-column type="index" label="序号" width="88" align="center">
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="180">
          </el-table-column>
          <el-table-column prop="date" label="属性值列表" width="540">
            <template slot-scope="{ row }">
              <el-tag
                type="success"
                v-for="value in row.attrValueList"
                :key="value.id"
                style="margin:10px"
              >
                {{ value.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作">
            <template slot-scope="{row,$index}">
              <el-button
                style="margin-right:10px"
                size="mini"
                type="warning"
                icon="el-icon-edit"
                @click="updateAttr(row)"
              ></el-button>
            <el-popconfirm :title="`确定删除${row.attrName}吗？`" @onConfirm="deleteAttr(row,$index)">
               <el-button
                size="mini"
                type="danger" slot="reference"
                icon="el-icon-delete"
                ></el-button>
             </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="!isshowtable">
        <el-form :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              style="width: 150px"
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
          <el-button type="primary" icon="el-icon-plus" @click="addattrValue"
          :disabled="!attrInfo.attrName"
          >添加属性值</el-button>
          <el-button @click="isshowtable = true">取消</el-button>
        </el-form>
        <el-table border style="width: 100%; margin: 20px 0" :data="attrInfo.attrValueList">
          <el-table-column type="index" label="序号" width="100" align="center" >
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称"> 
             <template slot-scope="{row,$index}">
              <el-input placeholder="请输入属性值名称" v-model="row.valueName"
              ref='input'
              v-if="row.isshowinput" size="mini" @blur=checkattrvalue(row,$index) @keyup.native.enter=checkattrvalue(row)></el-input>
               <span v-else @click="checkspan(row)" style="display:block" >{{row.valueName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="prop">
            <template slot-scope="{row,$index}">
              <!-- 气泡确认框 -->
              <el-popconfirm :title="`确定删除${row.valueName}吗？`" @onConfirm="deleteattrValue(row,$index)">
              <el-button
                type="danger"
                size="mini"
                slot="reference"
                icon="el-icon-delete"
              ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="AddandUpdateAttr" :disabled="!attrInfo.attrValueList.length">保存</el-button>
        <el-button @click="isshowtable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//按需引入深拷贝lodash
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: "attr_",
  data() {
    return {
      id1: "",
      id2: "",
      id3: "",
      attrList: [],
      //是否展示表单元素
      isshowtable: true,
      //收集属性名称和属性值展示
      attrInfo: {
        attrName: "",//属性名
        attrValueList: [   //属性值
        //点击进来不能有元素
        //   {
        //     attrId: 0, //多个属性值中每个属性值对应的id
        //     valueName: "",
        //   },
        ],
        categoryId: 0,//三级分类的id
        categoryLevel:3,
      },
    };
  },
  methods: {
    //1.展示平台属性（单独写成一个方法是因为后面数据发生改变都需要调用）
    async getAttrList() {
      let result = await this.$API.attr.reqcategoryList(
        this.id1,
        this.id2,
        this.id3
      );
      if (result.code === 200) {
        this.attrList = result.data;
      } else {
        console.log("获取全部数据失败！");
      }
    },
    //2.接受来自子组件三级联动id
    getcategoryId({ cateid, level }) {
      if (level === 1) {
        this.id1 = cateid;
        this.id2 = "";
        this.id3 = "";
      }
      if (level === 2) {
        this.id2 = cateid;
        this.id3 = "";
      }
      if (level === 3) {
        this.id3 = cateid;
        this.getAttrList();
      }
    },
   
    //3.添加属性值
    addattrValue(){
  
        this.attrInfo.attrValueList.push({
            attrID:this.attrInfo.id,
            valueName:'',
             //是否展示input输入框
           isshowinput:true,
        })

      this.$nextTick(() => {
      this.$refs.input.focus()
    })
    }, 
    //判断属性值不能为空(失去焦点)
    checkattrvalue(row,$index){
        //特殊情况1:为空
       if(!row.valueName.trim()){
         alert('属性值不能为空')
       }else{
       //特殊情况2：已经存在
       this.attrInfo.attrValueList.some((item,index)=>{
        if(row!==item&&row.valueName==item.valueName){
         return this.$message('该属性值已存在！')
          }
        else{
        row.isshowinput=false
       }
       })
       }
       
    },
    //点击span事件
    checkspan(row){
    row.isshowinput=true
     this.$nextTick(() => {
         this.$refs.input.focus()
    })
    },
    //4.添加属性(需要将数据清空)
    addAttr(){
       this.isshowtable = false
       this.attrInfo={
        attrName: "",
        attrValueList: [],
        categoryId: 0,
        categoryLevel:3,
      }
    },
    //5.删除属性值
    deleteattrValue(row,$index){
     this.attrInfo.attrValueList.splice($index,1)
    },
    //6.删除属性名
   async deleteAttr(row){
    try {
      let result=await this.$API.attr.reqDeleteAttr(row.id)
     if(result.code===200){
      this.attrList=this.attrList.filter(item=>{
        return item!==row
       })
    }
    } catch (error) {
      console.log("属性名删除失败！")
    }
    
  
    },
    //7.修改属性
    updateAttr(row){
      this.isshowtable = false
      this.attrInfo=cloneDeep(row)
      this.attrInfo.attrValueList.forEach(item=>{
        this.$set(item,'isshowinput',false)
      })
    },
    //5.保存数据发送请求
   async AddandUpdateAttr(){
        //情况1.出现很多空数组需要过滤
        this.attrInfo.attrValueList=this.attrInfo.attrValueList.filter(item=>{
          if(item.valueName!==''){
            delete item.isshowinput
            return true
          }
        })
        this.attrInfo.categoryId=this.id3
        try {
          //情况2：数据为空
          if(!this.attrInfo.attrValueList.length){
           return this.$message({type:"warning",message:'数据不能为空！'})
          }else{
            await this.$API.attr.reqAddandUpdateAttr(this.attrInfo)
            this.$message({type:'success',message:'保存成功'})
            this.getAttrList()
            this.isshowtable = true
          }
        } catch (error) {
        this.$message({type:'error',message:'保存失败'})
        }
    }
  },
};
</script>

<style>
</style>